package com.dibang.app.operation.control.impl;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.maps.TextureMapView;
import com.amap.api.maps.model.Marker;
import com.dibang.app.R;
import com.dibang.app.mvp.abs.AbsControl;
import com.dibang.app.mvp.util.DateUtils;
import com.dibang.app.mvp.util.XmlDB;
import com.dibang.app.operation.control.abs.MainControl;
import com.dibang.app.operation.model.abs.MainModel;
import com.dibang.app.operation.presenter.abs.MainPresenter;
import com.dibang.app.operation.provider.MainProImpl;
import com.dibang.app.operation.view.abs.MainView;
import com.dibang.app.ui.GroupMessageActivity;
import com.dibang.app.ui.LoginActivity;
import com.dibang.app.ui.SafeCenterActivity;
import com.dibang.app.ui.SelectByBusLocationActivity;
import com.dibang.app.ui.TripListActivity;
import com.dibang.app.view.DiffuseWaveView;
import com.dibang.app.view.UpScrollLayout;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zaaach.citypicker.model.City;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;

/**
 * Created by wxl on 2019/7/24.
 *
 */

public class MainControlImpl extends AbsControl<MainView, MainPresenter, MainModel, MainProImpl> implements MainControl {

    @BindView(R.id.scroll_down_layout)
    UpScrollLayout mScrollLayout;

    @BindView(R.id.diffse_view)
    DiffuseWaveView diffuseWaveView;

    @BindView(R.id.mapview)
    TextureMapView mapView;

    @BindView(R.id.main_route_info_layout)
    LinearLayout routeLayout;

    @BindView(R.id.main_location_adr_view)
    TextView adrTopTextView;

    @BindView(R.id.main_route_start_text)
    TextView routeStartTextView;

    @BindView(R.id.main_view_pager)
    ViewPager viewPager;

    @BindView(R.id.main_start_time_view)
    TextView startTimeView;

    @BindView(R.id.scroll_down_close_view)
    View openView;

    private Marker marker = null;

    private int peerPointer = 0;

    private boolean isOpen = true;

    public MainControlImpl(@NonNull View targetView) {
        super(targetView);
        ButterKnife.bind(this, targetView);
        EventBus.getDefault().register(this);
    }


    /**
     * 设置首页布局
     */
    @Override
    public void setMainViewExpandChanged() {
        routeLayout.setClickable(true);
        routeLayout.setEnabled(true);
        routeLayout.setFocusableInTouchMode(true);
        getView().onUpScrollLayoutChangedWaveViewExpand(mScrollLayout, diffuseWaveView);
        diffuseWaveView.setOnWaveViewStatusChangeListener(onWaveViewStatusChangeListener);
        getView().onMapViewExpand(mapView, marker);
        getView().onPeerTabSelectChanged(isOpen,peerPointer,rootView);
        getView().onViewPagerExpand(((AppCompatActivity) getContext()).getSupportFragmentManager(), viewPager);
    }


    /**
     * 是否打开和关闭互动窗口的监听
     */
    private DiffuseWaveView.OnWaveViewStatusChangeListener onWaveViewStatusChangeListener = new DiffuseWaveView.OnWaveViewStatusChangeListener() {
        @Override
        public void onStatusChange(boolean isOpen) {
            routeLayout.setBackgroundResource(isOpen ? R.drawable.shape_normal_white_bg : R.drawable.shap_top_radius_5_white_bg);
            MainControlImpl.this.isOpen = isOpen;
            openView.setVisibility(isOpen?View.VISIBLE:View.GONE);
            getView().onPeerTabSelectChanged(isOpen,peerPointer,rootView);
        }
    };





    @OnClick(R.id.main_peer_line_layout)
    public void onPeerViewClick(View v) {
        peerPointer = 0;
        getView().onPeerTabSelectChanged(isOpen,peerPointer,rootView);
        mScrollLayout.scrollToClose();
        viewPager.setCurrentItem(peerPointer);
    }


    @OnClick(R.id.main_peer_group_layout)
    public void onGroupViewClick(View v) {
        peerPointer = 1;
        getView().onPeerTabSelectChanged(isOpen,peerPointer,rootView);
        mScrollLayout.scrollToClose();
        viewPager.setCurrentItem(peerPointer);
    }


    @OnClick(R.id.main_route_info_layout)
    public void onStartAdrTextViewClick(View v){
        mScrollLayout.showOrHide();
    }


    @OnClick(R.id.main_view_user_info_view)
    public void onUserInfoViewClick(View v){
        v.getContext().startActivity(new Intent(v.getContext(), LoginActivity.class));
    }


    @OnClick(R.id.main_again_location_layout)
    public void onReloadLocationViewClick(View v){
        onGetLocationPermissions((FragmentActivity) getContext(), new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                if(aBoolean){
                    getView().reloadLocation();
                }
            }
        });
    }

    @OnClick(R.id.main_group_info_layout)
    public void onGroupMessageViewClick(View v){
        getContext().startActivity(new Intent(getContext(), TripListActivity.class));
    }

    @OnClick(R.id.main_current_city_layout)
    public void onSelectCurrentCityViewClick(View v){
        getView().onSelectCurrentCity((FragmentActivity) getContext());
    }

    @OnClick(R.id.main_start_time_layout)
    public void onSelectStartTimeClick(View v){
        getView().onSelectStartTime(getContext());
    }

    @OnClick(R.id.scroll_down_close_view)
    public void onOpenViewClick(View v){
        mScrollLayout.scrollToOpen();
    }

    @OnClick(R.id.main_safe_layout)
    public void onSafeCenterViewClick(View v){
        getContext().startActivity(new Intent(getContext(), SafeCenterActivity.class));
    }

    /**
     * 申请定位权限
     *
     * @param activity
     * @param onNext
     */
    @SuppressLint("CheckResult")
    private void onGetLocationPermissions(FragmentActivity activity, Consumer<Boolean> onNext) {
        new RxPermissions(activity)
                .request(Manifest.permission.ACCESS_FINE_LOCATION)//这里填写所需要的权限多个的话可以逗号隔开
                .subscribe(onNext);
    }


    @Override
    public void onLocationChanged(@NonNull AMapLocation aMapLocation) {
        XmlDB.get().put("city",aMapLocation.getCity())
        .put("lon",aMapLocation.getLongitude())
        .put("lat",aMapLocation.getLatitude());
        adrTopTextView.setText(aMapLocation.getCity());
        routeStartTextView.setText(aMapLocation.getAoiName() + aMapLocation.getDescription());
    }

    @Override
    public void onLocationFailed() {
        adrTopTextView.setText("定位失败");
    }

    @Override
    public void onPagerSelectChanged(int position) {
        peerPointer = position;
        getView().onPeerTabSelectChanged(isOpen,peerPointer,rootView);
    }


    @Override
    public void onSelectedStartTimeChanged(Date date) {
        startTimeView.setText(DateUtils.date2String(date,DateUtils.yyyyMMddHHmm.get()));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    @Override
    public void onSelectedCurrentCityChanged(City data) {
        XmlDB.get().put("city",data.getName())
                .put("lon",0)
                .put("lat",0);
        adrTopTextView.setText(data.getName());
        routeStartTextView.setText("");
    }



    @OnClick(R.id.main_route_start_layout)
    public void onSelectStartLocationClick(View v){
        getContext().startActivity(new Intent(getContext(),SelectByBusLocationActivity.class)
        .putExtra("where","start"));
    }


    @OnClick(R.id.main_route_end_layout)
    public void onSelectEndLocationClick(View v){
        getContext().startActivity(new Intent(getContext(),SelectByBusLocationActivity.class)
                .putExtra("where","end"));
    }



    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
